package cn.yunhe.servlet;

import cn.yunhe.entity.Order;
import cn.yunhe.entity.OrderCon;
import cn.yunhe.entity.merchantsentity.Food;
import cn.yunhe.entity.merchantsentity.MerchantsAccount;
import cn.yunhe.entity.merchantsentity.MerchantsData;
import cn.yunhe.entity.userentity.UserAccount;
import cn.yunhe.entity.userentity.UserData;
import cn.yunhe.util.AlipayConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import javafx.application.Application;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 李非凡
 * 支付宝支付servlet
 */
@WebServlet("/AlipayPayServlet")
public class AlipayPayServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //获取mid
        String mid=request.getParameter("mid");
        //商户订单号，商户网站订单系统中唯一订单号，必填
        Date date=new Date();
        SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
        String out_trade_no = df.format(date);
        //付款金额，必填
        String total_amount = request.getParameter("price");
        //订单名称，必填
        String subject = request.getParameter("fname");
        //商品描述，可空
        String body = request.getParameter("fname");
        Order order=new Order();
        order.setOid(out_trade_no);
        //mid
        MerchantsAccount merchantsAccount=new MerchantsAccount();
        merchantsAccount.setMid(Integer.parseInt(mid));
        MerchantsData merData=new MerchantsData();
        merData.setMerAccount(merchantsAccount);
        order.setMerData(merData);
        //uid
        UserAccount userAccount=new UserAccount();
        userAccount.setUid((int)(request.getSession().getAttribute("uid")));
        UserData userData=new UserData();
        userData.setUserAccount(userAccount);
        order.setUserData(userData);
        //金额
        order.setTotalPrice(Double.parseDouble(total_amount));
        //创建时间
        SimpleDateFormat df2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        order.setCreateDate(df2.format(date));
        //地址
        String address=request.getParameter("shi")+request.getParameter("jie");
        order.setAddress(address);

        //订单详情
        OrderCon orderCon=new OrderCon();
        Food food=new Food();
        int fid=Integer.parseInt(request.getParameter("fid"));
        food.setFid(fid);
        orderCon.setFood(food);
        //数量
        int count=Integer.parseInt(request.getParameter("count"));
        orderCon.setCount(count);
        //订单号
        orderCon.setOrder(order);

        ServletContext application=this.getServletContext();
        application.setAttribute("orderCon",orderCon);
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        out.println(result);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
